package com.hula.onion.book.server.spider.platforms.dianrongwang;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("dianRongWangSpider")
public class DianRongWangSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://auth.dianrong.com/auth-server/api/users/login/pwd";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.dianrong.com/api/v2/user/accountprofile";

    @Autowired
    private DianRongWangSpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);
            //1.2 模拟登陆
            String responseStr = HttpUtils.post(LOGIN_URL,
                    spiderHelper.installRequestParams(loginForm),
                    getHttpContext());
            DianRongWangResponseEntity responseEntity = JSONObject.parseObject(responseStr, DianRongWangResponseEntity.class);
            logger.info("[dianRongWangSpider] Http response result:{}", responseEntity.toString());
            if ("success".equals(responseEntity.getResult())) {
                //2.1 爬取用户详细信息
                String result = HttpUtils.get(GET_ACCOUNT_INFO_URL,getHttpContext());
                //2.2 解析HTML
                AccountInfo accountBalance = spiderHelper.parseAccountBalance(result);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountBalance);

            } else {
                commonResponse.setMsg(responseEntity.getErrors());
                commonResponse.setCode(responseEntity.getMessage());
            }
        return commonResponse;
    }
}
